﻿using Domain.Model;
using Infrastructure;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class LoginController : BasicController
    {
        //
        // GET: /Login/

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登录操作
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="password">密码</param>
        /// <param name="validCode">验证码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string account, string password, string validCode)
        {
            try
            {
                account = account.NullThenEmpty().Trim();
                password = password.NullThenEmpty().Trim();
                validCode = validCode.NullThenEmpty().Trim();

                var vCode = Session["ValidCode"];

                if (vCode == null)
                {
                    return Json(new { state = false, value = "会话已过期，请重新登录..." });
                }

                if (vCode.ToString() != validCode)
                {
                    return Json(new { state = false, value = "验证码错误..." });
                }

                if (account.IsNullOrEmpty() || password.IsNullOrEmpty())
                {
                    return Json(new { state = false, value = "账号或密码不能为空..." });
                }

                var user = this.DbContext.User.Where(u => u.Account == account).FirstOrDefault();

                if (user == null || user.Password != Infrastructure.Encryption.GetPasswordMd5(password))
                {
                    return Json(new { state = false, value = "账号或密码不正确..." });
                }

                if (user.IsValid == false)
                {
                    return Json(new { state = false, value = "账号已被冻结..." });
                }

                Session["LoginUser"] = JsonSerializer.ToEntity<User>(JsonSerializer.ToJson(user));

                return Json(new { state = true, value = "/member" });
            }
            catch(Exception ex)
            {
                return Json(new { state=false,value=ex.Message});
            }
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult ValidCode()
        {
            var validCode = Infrastructure.ValidCode.NewValidCode();
            Session["ValidCode"] = validCode;
            using (var image = Infrastructure.ValidCode.ValidCodeToImage(validCode))
            {
                using (var ms = new MemoryStream())
                {
                    image.Save(ms, ImageFormat.Gif);
                    Response.Cache.SetNoStore();
                    Response.ClearContent();
                    Response.ContentType = "image/Gif";
                    return File(ms.ToArray(), "image/Gif");
                }
            }
        }
        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            Response.Cookies.Clear();
            Response.Expires = 0;
            Session.Abandon();
            Session.Clear();
            return RedirectToAction("index", "system");
        }

        /// <summary>
        /// 检查账号
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="account">账号</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CheckAccount(Guid id, string account)
        {
            var exists = this.DbContext.User.Any(item => item.ID != id && item.Account == account);
            return Json(new { state = !exists, message = "此账号已被注册" });
        }
    }
}
